<template>
  <div class="dynamic-detail">
    <!-- 返回按钮 -->
    <div class="top-bar">
      <button class="back-btn" @click="goBack">← 返回</button>
      <div class="more-menu-wrapper">
        <el-dropdown trigger="click" @command="handleMenuCommand">
          <span class="more-btn">···</span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="report">举报</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 图片轮播 -->
    <div class="swiper-wrapper" v-if="dynamic.imagesUrl.length">
      <div class="image-container" @click="openPreview(currentIndex)">
        <img
          :src="dynamic.imagesUrl[currentIndex]"
          class="big-image"
          alt="预览图"
        />
        <div class="image-indicator">
          第 {{ currentIndex + 1 }} / {{ dynamic.imagesUrl.length }} 张
        </div>
      </div>

      <button class="prev" @click="prev" :disabled="currentIndex === 0">
        ←
      </button>
      <button
        class="next"
        @click="next"
        :disabled="currentIndex === dynamic.imagesUrl.length - 1"
      >
        →
      </button>
    </div>

    <!-- 用户信息 -->
    <div class="header">
      <img
        :src="dynamic.avatar"
        class="avatar"
        @click="goUserProfile(dynamic.authorId)"
      />
      <span class="username">{{ dynamic.username }}</span>
      <button
        class="follow-btn"
        :class="{ followed: dynamic.isFollowed }"
        @click="toggleFollow"
      >
        {{ dynamic.isFollowed ? '已关注' : '+ 关注' }}
      </button>
    </div>

    <!-- 自定义弹窗 -->
    <teleport to="body">
      <div v-if="showDialog" class="custom-dialog-mask">
        <div class="custom-dialog">
          <p class="dialog-text">
            你确定要{{ dialogActionText }} {{ dynamic.username }} 吗？
          </p>
          <div class="dialog-buttons">
            <button @click="handleDialogConfirm" class="confirm-btn">
              确认
            </button>
            <button @click="handleDialogCancel" class="cancel-btn">取消</button>
          </div>
        </div>
      </div>
    </teleport>

    <!-- 标题与内容 -->
    <h2 class="title">{{ dynamic.dynamicTitle }}</h2>
    <p class="content">{{ dynamic.dynamicContent }}</p>

    <!-- 话题和数据 -->
    <div class="footer">
      <div class="topics">
        <span
          class="topic"
          v-for="topic in dynamic.topics"
          :key="topic.topicId"
          @click="goTopic(topic.topicId)"
        >
          #{{ topic.topicName }}
        </span>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-section">
      <div class="comment-title-wrapper">
        <h3 class="comment-title">全部评论 {{ dynamic.commentCount }}</h3>
      </div>

      <!-- 使用递归组件 -->
      <CommentItem
        v-for="comment in comments"
        :key="comment.commentId"
        :comment="comment"
        :is-reply="false"
        @like="toggleLike"
        @select="handleSelect"
      />
    </div>

    <!-- 评论输入区域 -->
    <div class="link-reply__main-box">
      <!-- 新增回复预览 -->
      <div v-if="selectedComment" class="reply-preview">
        <div class="preview-content">
          <span class="reply-target"
            >回复 @{{ selectedComment.username }}：</span
          >
          <span class="original-comment">{{
            selectedComment.commentContent
          }}</span>
          <button @click="selectedComment = null" class="cancel-reply">
            ×
          </button>
        </div>
      </div>
      <div class="link-reply__input-wrapper">
        <div
          class="link-reply__editor"
          contenteditable="true"
          @input="handleInput"
          ref="editorRef"
          :class="{ expanded: editorExpanded }"
          @focus="expandEditor"
          @blur="shrinkEditor"
        ></div>
        <div v-if="!newComment" class="link-reply__placeholder">参与讨论</div>
        <div class="link-reply__operation-box">
          <template v-if="!editorExpanded">
            <button
              class="link-reply__operation-item"
              @click.stop="toggleDynamicLike"
            >
              <img
                :src="dynamic.isLiked ? likeBlack : likeWhite"
                class="like-icon"
              />
              <span class="link-reply__operation-desc">
                {{ dynamic.likeCount }}
              </span>
            </button>
            <button
              class="link-reply__operation-item"
              @click.stop="toggleFavorite"
            >
              <img
                :src="dynamic.isFavorite ? starBlack : starWhite"
                class="like-icon"
              />
              <span class="link-reply__operation-desc">
                {{ dynamic.favCount }}
              </span>
            </button>
            <button
              class="link-reply__operation-item"
              @click="expandCommentEditor"
            >
              <img src="@/assets/imgs/comment-icon.png" class="like-icon" />
              <span class="link-reply__operation-desc">{{
                dynamic.commentCount
              }}</span>
            </button>
          </template>
          <template v-else>
            <button class="link-reply__operation-item" @click="submitComment">
              <i class="hb-icon">💬</i>
              <span class="link-reply__operation-desc">发布</span>
            </button>
            <button class="link-reply__operation-item" @click="cancelComment">
              <i class="hb-icon">❌</i>
              <span class="link-reply__operation-desc">取消</span>
            </button>
          </template>
        </div>
      </div>
    </div>
    <ReportDialog v-model="showReportDialog" @submit="handleReportSubmit" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getDynamicDetail } from '@/apis/dynamic'
import { getComments, postComment } from '@/apis/comment'
import { likeTarget } from '@/apis/like'
import { favTarget } from '@/apis/fav'
import { followUser } from '@/apis/user'
import CommentItem from '@/views/Dynamic/components/CommentItem.vue'
import ReportDialog from '@/components/ReportDialog.vue'
import { reportTarget } from '@/apis/report' // 你封装的举报请求方法

import likeBlack from '@/assets/imgs/like-black.png'
import likeWhite from '@/assets/imgs/like-white.png'
import starBlack from '@/assets/imgs/star-black.png'
import starWhite from '@/assets/imgs/star-white.png'

const route = useRoute()
const router = useRouter()

// 动态数据
const dynamic = ref({
  dynamicId: 0,
  username: '',
  avatar: '',
  dynamicTitle: '',
  dynamicContent: '',
  imagesUrl: [],
  commentCount: 0,
  likeCount: 0,
  favCount: 0,
  topics: [],
})

// 图片切换逻辑
const currentIndex = ref(0)
const prev = () => currentIndex.value > 0 && currentIndex.value--
const next = () =>
  currentIndex.value < dynamic.value.imagesUrl.length - 1 &&
  currentIndex.value++

// 评论功能
const comments = ref([])
const editorRef = ref(null)
const editorExpanded = ref(false)
const newComment = ref(false)

// 输入框交互
const expandEditor = () => {
  editorExpanded.value = true
}

const shrinkEditor = () => {
  if (!newComment.value) {
    editorExpanded.value = false
  }
}
const handleInput = () => {
  newComment.value = editorRef.value.innerText.trim().length > 0
}
const selectedComment = ref(null)

const submitComment = async () => {
  const content = editorRef.value?.innerText?.trim() || ''

  // 新增空内容校验
  if (!content.length) {
    ElMessage.warning('评论内容不能为空')
    return
  }

  try {
    const params = {
      targetType: selectedComment.value ? 3 : 1,
      targetId: selectedComment.value
        ? selectedComment.value.commentId
        : dynamic.value.dynamicId,
      content,
      parentCommentId: selectedComment.value?.commentId || null,
      targetUserId:
        selectedComment.value?.commentUserId || dynamic.value.authorId,
    }

    await postComment(params)
    editorRef.value.innerText = ''
    newComment.value = false
    selectedComment.value = null
    await fetchComments()
    ElMessage.success('评论发布成功') // 新增成功提示
  } catch (error) {
    console.error('发布评论失败:', error)
    ElMessage.error('评论发布失败，请稍后重试') // 增强错误提示
  }
}

const handleSelect = (comment) => {
  if (selectedComment.value?.commentId === comment.commentId) {
    selectedComment.value = null
  } else {
    selectedComment.value = comment
    editorExpanded.value = true
    nextTick(() => editorRef.value.focus())
  }
}
const cancelComment = () => {
  editorRef.value.innerText = ''
  newComment.value = false
  editorExpanded.value = false
}

// 数据获取
const fetchDetail = async () => {
  const res = await getDynamicDetail(route.params.id)
  if (res.code === '200') dynamic.value = res.data
}

const fetchComments = async () => {
  const res = await getComments(route.params.id, 1)
  if (res.code === '200') comments.value = res.data
}

// 初始化
onMounted(async () => {
  await fetchDetail()
  await fetchComments()
  console.log(comments.value)
})

// 返回按钮
const goBack = () => router.back()
const goTopic = (topicId) => {
  router.push(`/home/topic/${topicId}`)
}
// 点赞功能
const toggleLike = async (comment) => {
  try {
    const newStatus = !comment.isLiked
    await likeTarget(comment.commentId, 3, newStatus)
    comment.isLiked = newStatus
    comment.commentLikesCount += newStatus ? 1 : -1
  } catch (error) {
    console.error('点赞操作失败:', error)
  }
}

const toggleDynamicLike = async () => {
  try {
    const newStatus = !dynamic.value.isLiked
    await likeTarget(dynamic.value.dynamicId, 1, newStatus) // targetType=1表示动态
    dynamic.value.isLiked = newStatus
    dynamic.value.likeCount += newStatus ? 1 : -1
  } catch (error) {
    console.error('动态点赞失败:', error)
  }
}

const toggleFavorite = async () => {
  try {
    const newStatus = !dynamic.value.isFavorite
    // 假设收藏使用相同API，需确认后端接口
    await favTarget(dynamic.value.dynamicId, 1, newStatus)
    dynamic.value.isFavorite = newStatus
    dynamic.value.favCount += newStatus ? 1 : -1
  } catch (error) {
    console.error('收藏操作失败:', error)
  }
}

const expandCommentEditor = () => {
  editorExpanded.value = true
  nextTick(() => {
    editorRef.value?.focus()
  })
}

//关注
const showDialog = ref(false)
const dialogActionText = ref('关注') // or '取消关注'
let nextFollowStatus = false // 临时变量保存下一状态

const toggleFollow = () => {
  // 设置状态并弹出弹窗
  nextFollowStatus = !dynamic.value.isFollowed
  dialogActionText.value = nextFollowStatus ? '关注' : '取消关注'
  showDialog.value = true
}

const handleDialogCancel = () => {
  showDialog.value = false
}

const handleDialogConfirm = async () => {
  showDialog.value = false
  try {
    const res = await followUser(dynamic.value.authorId, nextFollowStatus)
    if (res.code === '200') {
      dynamic.value.isFollowed = nextFollowStatus
      ElMessage.success(`${dialogActionText.value}成功`)
    } else if (res.code === 'A0220') {
      ElMessage.warning('自己不能关注自己哦')
    } else {
      ElMessage.error(`${dialogActionText.value}失败，请稍后再试`)
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    ElMessage.error('操作异常，请稍后重试')
  }
}

const goUserProfile = (userId) => {
  router.push(`/home/user/${userId}`)
}

const showReportDialog = ref(false)
const reportTargetData = ref({
  targetId: 0,
  targetType: 1, // 1 表示动态
})
const handleMenuCommand = (command) => {
  if (command === 'report') {
    reportTargetData.value.targetId = dynamic.value.dynamicId
    showReportDialog.value = true
  }
}
const handleReportSubmit = async (payload) => {
  try {
    const finalData = { ...payload, ...reportTargetData.value }
    await reportTarget(finalData)
    ElMessage.success('举报成功，感谢你的反馈')
  } catch (err) {
    console.error(err)
    ElMessage.error('举报失败，请稍后重试')
  }
}
</script>

<style scoped>
@import './dynamic-detail.css';
</style>
